package com.hxh.learn.config;


import com.hxh.learn.model.SysUser;
import com.hxh.learn.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import static com.hxh.common.constant.HxhConstant.USER_STATUS_NO;

/**
 * @Author: hxh
 * @Date: 2023/3/3
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private LoginUserDetailsServiceImpl loginUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取用户名称
        String name = authentication.getName();
        String password = (String) authentication.getCredentials();
        SysUser user = userService.getByName(name);
        UserDetails userDetails = loginUserDetailsService.loadUserByUsername(name);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在");
        } else {
            if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
                throw new BadCredentialsException("登录名或密码错误");
            } else if (USER_STATUS_NO.equals(user.getUserStatus())) {
                throw new BadCredentialsException("账户未启用请联系管理员");
            } else {
                return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
            }
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
